<template>
  <div class="admin-page admin-term">
    <div class="page-header">
      <h1>学期管理</h1>
      <div class="actions">
        <el-button type="primary" @click="openTermDialog(null)">
          <el-icon><Plus /></el-icon> 新增学期
        </el-button>
      </div>
    </div>
    
    <el-card class="table-card">
      <div class="filter-container">
        <el-form :inline="true" class="filter-form">
          <el-form-item label="学期名称">
            <el-input v-model="filters.name" placeholder="请输入学期名称" clearable></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="searchTerms">搜索</el-button>
            <el-button @click="resetFilters">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
      
      <el-table
        v-loading="loading"
        :data="filteredTerms"
        border
        stripe
        style="width: 100%"
      >
        <el-table-column prop="id" label="学期ID" width="100" resizable></el-table-column>
        <el-table-column prop="name" label="学期名称" min-width="120" resizable></el-table-column>
        <el-table-column prop="startDate" label="开始日期" width="120" resizable></el-table-column>
        <el-table-column prop="endDate" label="结束日期" width="120" resizable></el-table-column>
        <el-table-column label="当前学期" width="100" resizable>
          <template #default="scope">
            <el-tag type="success" v-if="scope.row.isCurrent">是</el-tag>
            <el-tag type="info" v-else>否</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" fixed="right" width="320" resizable>
          <template #default="scope">
            <el-button 
              size="small" 
              type="success" 
              v-if="!scope.row.isCurrent"
              @click="setCurrentTerm(scope.row)"
            >
              <el-icon><Check /></el-icon> 设为当前学期
            </el-button>
            <el-button size="small" type="primary" @click="openTermDialog(scope.row)">
              <el-icon><Edit /></el-icon> 编辑
            </el-button>
            <el-button size="small" type="danger" @click="deleteTerm(scope.row)">
              <el-icon><Delete /></el-icon> 删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <div class="pagination-container">
        <el-pagination
          background
          layout="total, prev, pager, next, jumper"
          :total="total"
          :page-size="pageSize"
          :current-page="currentPage"
          @current-change="handlePageChange"
        ></el-pagination>
      </div>
    </el-card>
    
    <!-- 学期编辑对话框 -->
    <el-dialog
      :title="isEdit ? '编辑学期' : '新增学期'"
      v-model="dialogVisible"
      width="500px"
      append-to-body
      @close="handleDialogClose"
    >
      <el-form :model="termForm" :rules="rules" ref="termFormRef" label-width="80px">
        <el-form-item label="学期名称" prop="name">
          <el-input v-model="termForm.name" placeholder="请输入学期名称"></el-input>
        </el-form-item>
        <el-form-item label="开始日期" prop="startDate">
          <el-date-picker
            v-model="termForm.startDate"
            type="date"
            placeholder="选择开始日期"
            style="width: 100%"
            value-format="YYYY-MM-DD"
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="结束日期" prop="endDate">
          <el-date-picker
            v-model="termForm.endDate"
            type="date"
            placeholder="选择结束日期"
            style="width: 100%"
            value-format="YYYY-MM-DD"
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="当前学期" prop="isCurrent">
          <el-switch v-model="termForm.isCurrent"></el-switch>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitTermForm" :loading="submitting">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, onMounted, computed, reactive, nextTick } from "vue";
import { termApi } from "@/api/base-data";
import { ElMessage, ElMessageBox } from "element-plus";
import { Plus, Edit, Delete, Check } from "@element-plus/icons-vue";

export default {
  components: {
    Plus,
    Edit,
    Delete,
    Check
  },
  setup() {
    const terms = ref([]);
    const loading = ref(false);
    const submitting = ref(false);
    const dialogVisible = ref(false);
    const termFormRef = ref(null);
    
    // 分页相关
    const currentPage = ref(1);
    const pageSize = ref(10);
    const total = ref(0);
    
    // 筛选条件
    const filters = reactive({
      name: ""
    });
    
    // 学期表单
    const termForm = reactive({
      id: "",
      name: "",
      startDate: "",
      endDate: "",
      isCurrent: false
    });
    
    const isEdit = computed(() => !!termForm.id);
    
    // 表单验证规则
    const rules = {
      name: [
        { required: true, message: "请输入学期名称", trigger: "blur" }
      ],
      startDate: [
        { required: true, message: "请选择开始日期", trigger: "change" }
      ],
      endDate: [
        { required: true, message: "请选择结束日期", trigger: "change" },
        { validator: (rule, value, callback) => {
          if (termForm.startDate && value && value < termForm.startDate) {
            callback(new Error("结束日期不能早于开始日期"));
          } else {
            callback();
          }
        }, trigger: "change" }
      ]
    };

    const fetchTerms = async () => {
      loading.value = true;
      try {
        terms.value = await termApi.getAllTerms();
        total.value = terms.value.length;
      } catch (error) {
        console.error("获取学期列表失败:", error);
        ElMessage.error("获取学期列表失败");
      } finally {
        loading.value = false;
      }
    };
    
    // 根据筛选条件过滤数据
    const filteredTerms = computed(() => {
      let filtered = terms.value;
      
      if (filters.name) {
        filtered = filtered.filter(term => 
          term.name.includes(filters.name)
        );
      }
      
      // 更新总数
      total.value = filtered.length;
      
      // 返回当前页的数据
      const startIndex = (currentPage.value - 1) * pageSize.value;
      return filtered.slice(startIndex, startIndex + pageSize.value);
    });
    
    // 搜索学期
    const searchTerms = () => {
      currentPage.value = 1;
    };
    
    // 重置筛选条件
    const resetFilters = () => {
      filters.name = "";
      currentPage.value = 1;
    };
    
    // 处理页码变化
    const handlePageChange = (page) => {
      currentPage.value = page;
    };
    
    // 强制重置学期表单
    const forceResetTermForm = () => {
      termForm.id = "";
      termForm.name = "";
      termForm.startDate = "";
      termForm.endDate = "";
      termForm.isCurrent = false;
    };
    
    // 打开学期编辑对话框
    const openTermDialog = async (term) => {
      // 总是先强制重置表单
      forceResetTermForm();
      
      if (term) {
        // 编辑模式：填充现有数据
        termForm.id = term.id;
        termForm.name = term.name;
        termForm.startDate = term.startDate;
        termForm.endDate = term.endDate;
        termForm.isCurrent = term.isCurrent;
      }
      
      dialogVisible.value = true;
      
      // 确保在对话框打开后清除验证状态
      await nextTick();
      if (termFormRef.value) {
        termFormRef.value.clearValidate();
      }
    };
    
    // 处理对话框关闭
    const handleDialogClose = async () => {
      forceResetTermForm();
      await nextTick();
      if (termFormRef.value) {
        termFormRef.value.clearValidate();
      }
    };
    
    // 提交学期表单
    const submitTermForm = async () => {
      if (!termFormRef.value) return;
      
      try {
        await termFormRef.value.validate();
        submitting.value = true;
        
        if (isEdit.value) {
          await termApi.updateTerm(termForm.id, termForm);
          ElMessage.success("更新学期成功");
        } else {
          await termApi.createTerm(termForm);
          ElMessage.success("创建学期成功");
        }
        
        dialogVisible.value = false;
        fetchTerms();
      } catch (error) {
        console.error("提交学期表单失败:", error);
        ElMessage.error("操作失败");
      } finally {
        submitting.value = false;
      }
    };

    // 删除学期
    const deleteTerm = async (term) => {
      try {
        await ElMessageBox.confirm(`确定要删除学期 ${term.name} 吗？`, "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        });
        
        await termApi.deleteTerm(term.id);
        ElMessage.success("删除成功");
        fetchTerms();
      } catch (error) {
        if (error !== "cancel") {
          console.error("删除学期失败:", error);
          ElMessage.error(`删除学期失败: ${error.message || '未知错误'}`);
        }
      }
    };

    // 设置当前学期
    const setCurrentTerm = async (term) => {
      try {
        await ElMessageBox.confirm(`确定要将 ${term.name} 设为当前学期吗？`, "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "info"
        });
        
        await termApi.setCurrentTerm(term.id);
        ElMessage.success(`已将 ${term.name} 设为当前学期`);
        fetchTerms();
      } catch (error) {
        if (error !== "cancel") {
          console.error("设置当前学期失败:", error);
          ElMessage.error("操作失败");
        }
      }
    };

    onMounted(fetchTerms);

    return {
      terms,
      filteredTerms,
      loading,
      filters,
      currentPage,
      pageSize,
      total,
      termForm,
      termFormRef,
      rules,
      dialogVisible,
      submitting,
      isEdit,
      searchTerms,
      resetFilters,
      handlePageChange,
      openTermDialog,
      submitTermForm,
      deleteTerm,
      setCurrentTerm,
      handleDialogClose,
      forceResetTermForm
    };
  }
};
</script>

<style scoped>
.admin-term {
  padding: 0;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-header h1 {
  font-size: 22px;
  font-weight: 600;
  color: #303133;
  margin: 0;
}

.actions {
  margin-left: auto;
}

.table-card {
  margin-bottom: 20px;
}

.filter-container {
  margin-bottom: 20px;
}

.filter-form {
  display: flex;
  flex-wrap: wrap;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

:deep(.el-dialog__body) {
  padding-top: 10px;
}

:deep(.el-dialog__footer) {
  padding-top: 0;
}
</style>
